Access Linkedin Profile In Web App With Python3-linkedin, OAUTH2

Overview:

Retrieving the basic profile of a LinkedIn user from a web application using the Python API python3-linkedin involves the following steps:

  1. After access grant from the user, an OAUTH 2.0 access token for LinkedIn access is obtained from the Return_URL provided by the developer. Read this article to understand the steps involved in getting the OAuth2 access token for linkedin.
  2. The access token is passed on to the LinkedInApplication constructor to create an application instance.
  3. The get_profile() method is invoked on the LinkedInApplication instance, which returns the basic user profile as a Python dictionary.
  4. Using the Python json module, the Python dictionary is converted into a JSON string and printed on the web page/web application.
  5. All the above steps are performed by the Python code which handles the Return_URL. In this case, the Python class AppHome hosted in CherryPy.

Example:

# Example Web Application that accesses basic profile a #LinkedIn user using OAUTH2.0 and python3-linkedin API

 

# imports

import os.path

import json

import io

 

# import CherryPy

import cherrypy

 

# import the python3-linkedin api wrapper

from linkedin import linkedin

from linkedin import server

 

# Authorize the web application user to access LinkedIn services using OAuth2

applicationKey      = "xxxxxxxxxxxxxx"

applicationSecret   = " xxxxxxxxxxxxxxxx"

retURL              = "http://localhost:8080"

authentication      = linkedin.LinkedInAuthentication( applicationKey,

                                               applicationSecret,

                                               retURL,

                                               [linkedin.PERMISSIONS.BASIC_PROFILE]

                                             )

# Get the authorization URL

authorizationURL = authentication.authorization_url                        

 

# Serves the LinkedIn authorization page

class LinkedInAuthorization:

    @cherrypy.expose

    def index(self):

        # redirect to LinkedIn authorization URL happens here

        raise cherrypy.HTTPRedirect(authorizationURL)

  

# Class for initial app home page and the post authorization app home page a.k.a return-URL

# The post authorization page displays the basic user profile as a JSON string

class HomeProfile:

    @cherrypy.expose

    def index(self, *args, **kwargs):

 

        content = io.StringIO()

 

        # Home page case - after authorization

        if len(kwargs) > 0:

            authCode                            = kwargs["code"]

            authentication.authorization_code   = authCode

            token                               = authentication.get_access_token();

            

            application     = linkedin.LinkedInApplication(token=token.access_token)

            basicProfile    = application.get_profile()

 

            profileString   = json.dumps(basicProfile)           

            content.write(json.dumps(profileString, indent=4, sort_keys=True))

           

 

            output = content.getvalue()

            content.close()       

       

            return [bytes(output, 'utf-8')]                   

       

        # Home page case - before authorization

        content.write('<html>')

        content.write('<head>')

        content.write('<title>')

        content.write('Sample web application that gets LinkedIn access and prints basic user profile')

        content.write('</title>')

        content.write('</head>')

       

        content.write('<body>')

        content.write('<h1>Sample web application that prints LinkedIn basic user profile using OAUTH 2.0</h1>')

        content.write('<p>Sample web application that gets Linkedin authorization from the ')

        content.write('user and prints the basic user profile</p>')

        content.write('<form action="for_linkedin_access" method="post">')

        content.write('<input type="submit" value="Authorize Sample Application for Linkedin Access">')

        content.write('</form>')       

        content.write('</body>')

       

        output = content.getvalue()

        content.close()       

       

        return [bytes(output, 'utf-8')]       

       

conf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')

 

if __name__ == '__main__':

    cherrypy.tree.mount(HomeProfile(),                 '/', config=conf)

    cherrypy.tree.mount(LinkedInAuthorization(),        '/for_linkedin_access', config=conf)

    cherrypy.engine.start()

    cherrypy.engine.block()   

 

 

Output:

{"siteStandardProfileRequest": {"url": "https://www.linkedin.com/profile/view?id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&authType=name&authToken=xxxx&trk=api*a5522416*s5724316*"}, "id": "xxxxxxxxxx", "lastName": "userLastName", "headline": "Position of the user", "firstName": "User First Name"}

 


Copyright 2023 © pythontic.com